<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :xs="24" :sm="24" :md="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" link @click="handleEdit">
                修改信息
              </el-button>
            </div>
          </template>
          <div class="user-profile">
            <div class="avatar-container">
              <el-avatar
                :size="100"
                :src="userStore.userInfo?.avatar"
                @click="handleAvatarClick"
              />
              <div class="avatar-mask" @click="handleAvatarClick">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
            <div class="info-list">
              <div class="info-item">
                <span class="label">用户名：</span>
                <span class="value">{{ userStore.userInfo?.username }}</span>
              </div>
              <div class="info-item">
                <span class="label">昵称：</span>
                <span class="value">{{ userStore.userInfo?.nickname }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱：</span>
                <span class="value">{{ userStore.userInfo?.email }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号：</span>
                <span class="value">{{ userStore.userInfo?.phone }}</span>
              </div>
              <div class="info-item">
                <span class="label">角色：</span>
                <span class="value">
                  <el-tag
                    v-for="role in userStore.userInfo?.roles"
                    :key="role"
                    size="small"
                    style="margin-right: 4px"
                  >
                    {{ role }}
                  </el-tag>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 修改密码卡片 -->
      <el-col :xs="24" :sm="24" :md="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入原密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdatePassword">
                保存修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改信息对话框 -->
    <el-dialog
      v-model="dialog.visible"
      title="修改信息"
      width="500px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 头像上传组件 -->
    <pro-upload
      v-model="avatar"
      ref="uploadRef"
      :action="uploadAction"
      :headers="uploadHeaders"
      type="image"
      :crop="true"
      :cropper-fixed="true"
      :cropper-fixed-number="[1, 1]"
      accept="image/*"
      style="display: none"
      @success="handleAvatarSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { Camera } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import { useUserStore } from "@/store/user";
import { updatePassword } from "@/api/system/user";

const userStore = useUserStore();

// 修改信息相关
const dialog = reactive({
  visible: false,
});

const formRef = ref<FormInstance>();
const form = reactive({
  nickname: "",
  email: "",
  phone: "",
});

const rules = {
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

const handleEdit = () => {
  dialog.visible = true;
  Object.assign(form, {
    nickname: userStore.userInfo?.nickname,
    email: userStore.userInfo?.email,
    phone: userStore.userInfo?.phone,
  });
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    // TODO: 调用更新用户信息接口
    ElMessage.success("修改成功");
    dialog.visible = false;
    userStore.getUserInfo(); // 刷新用户信息
  } catch (error: any) {
    ElMessage.error(error.message || "修改失败");
  }
};

// 修改密码相关
const passwordFormRef = ref<FormInstance>();
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const passwordRules = {
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return;

  try {
    await passwordFormRef.value.validate();
    await updatePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });
    ElMessage.success("修改成功");
    passwordForm.oldPassword = "";
    passwordForm.newPassword = "";
    passwordForm.confirmPassword = "";
  } catch (error: any) {
    ElMessage.error(error.message || "修改失败");
  }
};

// 头像上传相关
const uploadRef = ref();
const avatar = ref("");
const uploadAction = "/api/upload"; // 上传地址
const uploadHeaders = {
  Authorization: `Bearer ${userStore.token}`,
};

const handleAvatarClick = () => {
  uploadRef.value?.formRef?.click();
};

const handleAvatarSuccess = async (response: any) => {
  // TODO: 调用更新头像接口
  ElMessage.success("头像更新成功");
  userStore.getUserInfo(); // 刷新用户信息
};
</script>

<style lang="scss" scoped>
.profile-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .user-profile {
    display: flex;
    flex-direction: column;
    align-items: center;

    .avatar-container {
      position: relative;
      margin-bottom: 20px;
      cursor: pointer;

      .avatar-mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #fff;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        opacity: 0;
        transition: opacity 0.3s;

        .el-icon {
          font-size: 24px;
          margin-bottom: 4px;
        }

        span {
          font-size: 12px;
        }
      }

      &:hover .avatar-mask {
        opacity: 1;
      }
    }

    .info-list {
      width: 100%;

      .info-item {
        display: flex;
        margin-bottom: 16px;

        .label {
          width: 80px;
          color: #909399;
        }

        .value {
          flex: 1;
          color: #303133;
        }
      }
    }
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .profile-container {
    .el-col {
      margin-bottom: 20px;
    }
  }
}
</style>
